import os

# 打开文件
# f = open('test.txt')  # 相对路径
path = os.getcwd()
filename = path + '/test.txt'
file = open(filename, mode='r', encoding='utf-8')  # 绝对路径

# 读取整个文件
all_data: str = file.read()
print("all_data", all_data)

# 类似java，关闭文件流
file.close()

file = open("test.txt", mode='r', encoding='utf-8')
context = file.readlines()

# 实现wordcount
word_count_dict: dict[str, int] = {}

for e in context:
    # 去除行末的换行符
    line = e.strip()
    print("每一行元素:", line)
    for word in line.split():
        if word in word_count_dict:
            word_count_dict[word] += 1
        else:
            word_count_dict[word] = 1

# 按照value降序排序
word_count_list = sorted(word_count_dict.items(), key=lambda x: (x[1], x[0]), reverse=True)

# 打印数据
for (k, v) in word_count_list:
    print(f"key: {k}, value: {v}")

# # 关闭文件
file.close()
